package py.com.alfa.escriba.gui.controller;

import java.io.Serializable;
import java.util.Locale;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.thymeleaf.TemplateEngine;
import org.winter.dialect.response.JsonResponse;
import org.winter.utils.command.ControllerObject;

import py.com.alfa.escriba.gui.controller.object.referencia.DepartamentosControllerObject;
import py.com.alfa.escriba.gui.controller.view.View;
import py.com.alfa.escriba.gui.controller.view.ViewManager;
import py.com.alfa.escriba.gui.dto.admin.DepartamentoDTO;
import py.com.alfa.escriba.gui.rest.services.ReferenciaService;
import py.com.alfa.escriba.gui.session.SystemInfo;
import py.com.alfa.escriba.gui.spring.processors.SpringBean;
import py.com.sif.rest.client.spring.exception.RestClientException;

@Controller
@Scope("session")
@SessionAttributes("departamentos")
@RequestMapping("/departamentos")
public class DepartamentosController implements Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = 4845167048299228510L;
	private final static String PAGE_NAME = "pag:localidades";
	private final static String CONTROLLER_OBJECT_NAME = "departamentos";
	
	private Logger log = LoggerFactory.getLogger(getClass());
	@SpringBean private ReferenciaService referenciaService;
	@SpringBean private SystemInfo systemInfo;
	@SpringBean private ViewManager viewManager;
	@Autowired
	private ServletContext servletContext;
	@Autowired
	private TemplateEngine templateEngine;
	@ControllerObject
	private DepartamentosControllerObject departamentos;	
	private Locale locale;
	
	public DepartamentosController() {
		this.loadObjects();
	}

	private void loadObjects() {
		setLocale(LocaleContextHolder.getLocale());
	}

	private String verifAuto() {
		Subject subject = SecurityUtils.getSubject();
		if (subject == null || !subject.isAuthenticated()) {
			return "redirect:/";
		}		
		Boolean permitted = subject.isPermitted(DepartamentosController.PAGE_NAME);
		systemInfo.setSystemError(false);
		if (!permitted) {
			systemInfo.setSystemError(true);
			systemInfo.setErrorMessage("El usuario no esta autorizado para utilizar este recurso");
			return "error";
		}
		return null;
	}
	
	/**
	 * Simply selects the home view to render by returning its name.
	 */
	@RequestMapping(value = "/", method = RequestMethod.GET)
	public String homePage(Model model, HttpServletRequest request, HttpServletResponse response) {
		this.log.debug("Departamentos!");
		try {
			this.getDepartamentos().view().disable().localidades();
			String auto = this.verifAuto();
			if ( auto != null ) {
				return auto;
			}			
			this.getDepartamentos().setDepartamentos(this.referenciaService.obtenerDepartamentos());
			this.getDepartamentos().view().enable().localidades();
		} catch (Exception e) {
			this.log.error(e.getMessage(), e);
		}
		return View.DEPARTAMENTOS;
	}
	
	@RequestMapping(value = "/crear", method = RequestMethod.POST)
	public @ResponseBody JsonResponse crear(Model model,HttpServletRequest request,HttpServletResponse response,
			                                @ModelAttribute(CONTROLLER_OBJECT_NAME) DepartamentosControllerObject controllerObject,
			                                BindingResult bindingResult) {
		this.log.info("\n==============\nCREANDO!\n==============\n");
		JsonResponse jresponse = JsonResponse.getInstance(View.DEPARTAMENTOS);
		WebApplicationContext wac = WebApplicationContextUtils.getWebApplicationContext(servletContext);
		try {
			this.log.info("\n==============\nDEPARTAMENTOS : {} - {}!\n==============\n",controllerObject.getDepartamento());
			
			this.referenciaService.crearDepartamento(controllerObject.getDepartamento());
			this.getDepartamentos().getDepartamentos().add(controllerObject.getDepartamento());
			controllerObject.setDepartamento(null);
			this.setDepartamentos(controllerObject);
		} catch (Exception e) {
			this.log.error(e.getMessage(), e);
			if (e.getCause() != null && e.getCause() instanceof RestClientException) {
				return jresponse.error(e.getCause().getMessage());
			}
		}
		model.addAttribute(CONTROLLER_OBJECT_NAME, this.getDepartamentos());
		return jresponse.success(request, response, wac, model, templateEngine);
	}
	
	@RequestMapping(value = "/nuevoDepartamento", method = RequestMethod.POST)
	public @ResponseBody JsonResponse nuevo(Model model,HttpServletRequest request,HttpServletResponse response,
			                                @ModelAttribute(CONTROLLER_OBJECT_NAME) DepartamentosControllerObject controllerObject,
			                                BindingResult bindingResult) {
		this.log.info("\n==============\nNUEVO!\n==============\n");
		JsonResponse jresponse = JsonResponse.getInstance(View.DEPARTAMENTOS);
		WebApplicationContext wac = WebApplicationContextUtils.getWebApplicationContext(servletContext);
		try {
			this.getDepartamentos().setDepartamento(null);
			this.getDepartamentos().view().enable().nuevo().disable().editar();
			this.setDepartamentos(controllerObject);
		} catch (Exception e) {
			this.log.error(e.getMessage(), e);
			if (e.getCause() != null && e.getCause() instanceof RestClientException) {
				return jresponse.error(e.getCause().getMessage());
			}
		}
		model.addAttribute(CONTROLLER_OBJECT_NAME, this.getDepartamentos());
		return jresponse.success(request, response, wac, model, templateEngine);
	}

	@RequestMapping(value = "/eliminar/{index}", method = RequestMethod.POST)
	public @ResponseBody JsonResponse eliminar(Model model,HttpServletRequest request, HttpServletResponse response, @PathVariable("index") String ind) {
		this.log.info("\n==============\nELIMINANDO! {}\n==============\n", ind);
		JsonResponse jresponse = JsonResponse.getInstance(View.DEPARTAMENTOS);
		WebApplicationContext wac = WebApplicationContextUtils.getWebApplicationContext(servletContext);
		try {
			Integer index = Integer.parseInt(ind);
			DepartamentoDTO obj = this.getDepartamentos().getDepartamentos().get(index);
			this.log.info("DEPARTAMENTO: {}", obj);
			
			this.referenciaService.eliminarDepartamento(obj.getId());
            this.getDepartamentos().getDepartamentos().remove(obj);
		} catch (Exception e) {
			this.log.error(e.getMessage(), e);
			if (e.getCause() != null && e.getCause() instanceof RestClientException) {
				return jresponse.error(e.getCause().getMessage());
			}
		}
		model.addAttribute(CONTROLLER_OBJECT_NAME, this.getDepartamentos());
		return jresponse.success(request, response, wac, model, templateEngine);
	}
	
	@RequestMapping(value = "/editar/{index}", method = RequestMethod.POST)
	public @ResponseBody JsonResponse editar(Model model, HttpServletRequest request, HttpServletResponse response,
			                                 @PathVariable("index") String ind) {
		this.log.info("\n==============\nEDITANDO! DEPARTAMENTO\n==============\n");
		JsonResponse jresponse = JsonResponse.getInstance(View.DEPARTAMENTOS);
		WebApplicationContext wac = WebApplicationContextUtils.getWebApplicationContext(servletContext);
		try {
			Integer index = Integer.parseInt(ind);
			DepartamentoDTO obj = this.getDepartamentos().getDepartamentos().get(index);
			this.getDepartamentos().setDepartamento(obj);
			this.getDepartamentos().view().disable().nuevo().enable().editar();
		} catch (Exception e) {
			this.log.error(e.getMessage(), e);
			if (e.getCause() != null && e.getCause() instanceof RestClientException) {
				return jresponse.error(e.getCause().getMessage());
			}
		}
		model.addAttribute(CONTROLLER_OBJECT_NAME, this.getDepartamentos());
		return jresponse.success(request, response, wac, model, templateEngine);
	}
	
	@RequestMapping(value = "/actualizar", method = RequestMethod.POST)
	public @ResponseBody JsonResponse guardarEdicion(Model model, HttpServletRequest request, HttpServletResponse response,
			                                         @ModelAttribute(CONTROLLER_OBJECT_NAME) DepartamentosControllerObject controllerObject,
			                                         BindingResult bindingResult) {
		this.log.info("\n==============\nEDITANDO DEPARTAMENTOS!\n==============\n");
		JsonResponse jresponse = JsonResponse.getInstance(View.DEPARTAMENTOS);
		WebApplicationContext wac = WebApplicationContextUtils.getWebApplicationContext(servletContext);
		try {
			this.log.info("\n==============\nDEPARTAMENTOS: {}!\n==============\n", controllerObject.getDepartamento());
			this.referenciaService.actualizarDepartamento(controllerObject.getDepartamento());
			controllerObject.setDepartamento(null);
			this.getDepartamentos().view().disable().nuevo().disable().editar();
			this.setDepartamentos(controllerObject);
		} catch (Exception e) {
			this.log.error(e.getMessage(), e);
			if (e.getCause() != null && e.getCause() instanceof RestClientException) {
				return jresponse.error(e.getCause().getMessage());
			}
		}
		model.addAttribute(CONTROLLER_OBJECT_NAME, this.getDepartamentos());
		return jresponse.success(request, response, wac, model, templateEngine);
	}
	
	@RequestMapping(value = "/cancelar", method = RequestMethod.POST)
	public @ResponseBody JsonResponse cancelar(Model model, HttpServletRequest request, HttpServletResponse response,
                                               @ModelAttribute(CONTROLLER_OBJECT_NAME) DepartamentosControllerObject controllerObject, BindingResult bindingResult) {
		this.log.info("\n==============\nCancelar!\n==============\n");
		JsonResponse jresponse = JsonResponse.getInstance(View.DEPARTAMENTOS);
		WebApplicationContext wac = WebApplicationContextUtils.getWebApplicationContext(servletContext);
		try {
			controllerObject.setDepartamento(null);
			this.getDepartamentos().view().disable().nuevo().disable().editar();
			this.setDepartamentos(controllerObject);
		} catch (Exception e) {
			this.log.error(e.getMessage(), e);
			if (e.getCause() != null && e.getCause() instanceof RestClientException) {
				return jresponse.error(e.getCause().getMessage());
			}
		}
		model.addAttribute(CONTROLLER_OBJECT_NAME, this.getDepartamentos());
		return jresponse.success(request, response, wac, model, templateEngine);
	}

	
	@ModelAttribute(CONTROLLER_OBJECT_NAME)
	public DepartamentosControllerObject getDepartamentos() {
		return this.departamentos;
	}
	
	public void setDepartamentos(DepartamentosControllerObject listas) {
		this.departamentos = listas;
	}

	public Locale getLocale() {
		return locale;
	}

	public void setLocale(Locale locale) {
		this.locale = locale;
	}	
}
